<template>
  <div>
    你的购物车有如下商品：

    <el-table :data="cartList" border style="width: 100%">
      <el-table-column prop="product.name" label="商品名" width="180"/>
      <el-table-column prop="product.price" label="单价"/>
      <el-table-column prop="product.createAddr" label="产地"/>
      <el-table-column label="购买数量">
        <template #default="scope">
          <el-input v-model="scope.row.buyNum" @blur="updateNum(scope.row)"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="单项总价">
        <template #default="scope">
          {{ scope.row.product.price * scope.row.buyNum }}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button
              size="small"
              type="danger"
              @click="del(scope.row)">移除商品
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div>购物车总价：{{ getSumPrice() }}</div>

    <el-button type="primary" @click="$router.push('/shopIndex')">继续购物</el-button>
    <el-button type="primary" @click="$router.push('/order')">结账</el-button>


  </div>
</template>

<script>
import axios from "axios"

export default {
  data() {
    return {
      cartList: [],
    }
  },
  created() {
    this.findCart();
  },
  methods: {
    findCart() {
      axios.get("/project/cart/findByUserId").then(resp => {
        this.cartList = resp.data;
      })
    },
    updateNum(cartObj) {
      axios.get("/project/cart/updateNum", {
        params: {
          cartId: cartObj.id,
          num: cartObj.buyNum,
        }
      }).then(resp => {
        if (resp.data == "ok") {
          this.findCart();
        }
      })
    },
    del(obj) {
      axios.get("/project/cart/del", {params: {cartId: obj.id}}).then(resp => {
        if (resp.data == "ok") {
          this.findCart();
        }
      })
    },
    getSumPrice() {
      var sumPrice = 0;
      this.cartList.forEach(n => {
        sumPrice += n.buyNum * n.product.price;
      })
      return sumPrice;
    },
  }
}

</script>

<style scoped>

</style>